package server.handler;

import java.awt.Point;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.HashMap;

import server.command.Command;
import server.command.MarkCommand;
import server.ppt.PptScaler;

public class MarkCommandHandler extends CommandHandler {

	private Robot robot;
	private static HashMap<Integer, LinkedList<Point>> points = new HashMap<Integer, LinkedList<Point>>();

	public MarkCommandHandler(Robot robot) {
		this.robot = robot;
	}

	@Override
	public void handle(Command command) {
		MarkCommand mc = (MarkCommand) command;
		this.jmpSlide(mc.getPosition());
		this.changeToPen();
		switch (mc.getType()) {
		case MarkCommand.MARK_PRESS:
			robot.mouseMove(mc.getX() + PptScaler.getXOffset(), mc.getY()
					+ PptScaler.getYOffset());
			robot.mousePress(MouseEvent.BUTTON1_MASK);
			LinkedList<Point> list = points.get(mc.getPosition());
			if (list == null) {
				list = new LinkedList<Point>();
				points.put(mc.getPosition(), list);
			}
			list.add(new Point(mc.getX() + PptScaler.getXOffset(), mc.getY()
					+ PptScaler.getYOffset()));
			break;
		case MarkCommand.MARK_DRAG:
			robot.mouseMove(mc.getX() + PptScaler.getXOffset(), mc.getY()
					+ PptScaler.getYOffset());
			break;
		case MarkCommand.MARK_RELEASE:
			robot.mouseRelease(MouseEvent.BUTTON1_MASK);
			break;
		default:
			break;
		}
	}

	private void jmpSlide(Integer index) {
		String str = index.toString();
		for (int i = 0; i < str.length(); i++) {
			robot.keyPress(str.charAt(i));
			robot.keyRelease(str.charAt(i));
		}
		robot.keyPress(KeyEvent.VK_ENTER);
		robot.keyRelease(KeyEvent.VK_ENTER);
	}

	private void changeToPen() {
		robot.keyPress(KeyEvent.VK_CONTROL);
		robot.keyPress(KeyEvent.VK_P);
		robot.keyRelease(KeyEvent.VK_P);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	}

	public static Point getPrePoint(int index) {
		LinkedList<Point> list = points.get(index);
		if (list != null && list.size() > 0)
			return list.remove(list.size() - 1);
		return null;
	}
}
